import axios from 'axios'
import {wechatPayConfig} from '../config/wechat.js'

/**
 * 获取用户 OpenID
 */
export async function getOpenId(req, res) {
  try {
    const {code} = req.body

    if (!code) {
      return res.status(400).json({
        success: false,
        error: '缺少 code 参数'
      })
    }

    const appSecret = process.env.WECHAT_APP_SECRET

    if (!appSecret) {
      return res.status(500).json({
        success: false,
        error: '未配置 WECHAT_APP_SECRET'
      })
    }

    // 调用微信接口获取 openid
    const response = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
      params: {
        appid: wechatPayConfig.appId,
        secret: appSecret,
        js_code: code,
        grant_type: 'authorization_code'
      }
    })

    const {openid, session_key, errcode, errmsg} = response.data

    if (errcode) {
      console.error('获取 openid 失败:', errcode, errmsg)
      return res.status(500).json({
        success: false,
        error: errmsg || '获取 openid 失败'
      })
    }

    res.json({
      success: true,
      data: {
        openid,
        session_key
      }
    })
  } catch (error) {
    console.error('获取 openid 失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '获取 openid 失败'
    })
  }
}
